package com.light.gulimall.order.web;

import com.light.gulimall.order.dto.SubmitOrderDTO;
import com.light.gulimall.order.service.OrderService;
import com.light.gulimall.order.vo.OrderConfirmVO;
import com.light.gulimall.order.vo.SubmitOrderResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model) {

        OrderConfirmVO vo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData", vo);

        return "confirm";
    }

    @PostMapping("/submitOrder")
    public String submitOrder(SubmitOrderDTO dto, Model model, RedirectAttributes redirectAttributes) {
//        System.out.println("获取到的dto"+dto);
        SubmitOrderResponseVO vo = orderService.submitOrder(dto);

        if (vo.getCode() == 0) {
            model.addAttribute("submitOrderResp", vo);
            return "pay";
        } else {
            //错误则返回下单页面重新下单
            Integer code = vo.getCode();
            String msg = null;
            switch (code) {
                case 1:
                    msg = "请勿重复提交！";
                    break;
                case 2:
                    msg = "订单商品金额有变化，请检查后重新提交！";
                    break;
                case 3:
                    msg = "库存锁定失败，商品数量不足";
                    break;
            }
            redirectAttributes.addFlashAttribute("msg", msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }

    }


}
